package com.example.util;

import com.example.entity.Admin;
import com.example.repository.AdminRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * 管理员数据初始化器
 * 用于创建默认的管理员账号
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AdminDataInitializer implements CommandLineRunner {
    
    private final AdminRepository adminRepository;
    private final PasswordEncoder passwordEncoder;
    
    @Override
    public void run(String... args) throws Exception {
        createDefaultAdmin();
    }
    
    private void createDefaultAdmin() {
        try {
            // 检查是否已存在管理员账号
            if (adminRepository.findByUsernameOrPhone("admin", "13900139000").isPresent()) {
                log.info("管理员账号已存在，跳过创建");
                return;
            }

            // 创建默认管理员账号
            Admin admin = new Admin();
            admin.setUsername("admin");
            admin.setPhone("13900139000");  // 生产环境的管理员手机号
            admin.setPassword(passwordEncoder.encode("123456"));
            admin.setRealName("超级管理员");
            admin.setEmail("admin@laundrycare.com");
            admin.setRole(Admin.AdminRole.SUPER_ADMIN);
            admin.setPermissions("[\"user:view\", \"user:edit\", \"user:delete\", \"merchant:view\", \"merchant:edit\", \"merchant:delete\", \"merchant:approve\", \"order:view\", \"order:edit\", \"payment:view\", \"system:config\", \"system:log\", \"announcement:manage\", \"coupon:manage\", \"statistics:view\"]");
            admin.setStatus(Admin.AdminStatus.ACTIVE);

            adminRepository.save(admin);

            log.info("=== 管理员账号创建成功 ===");
            log.info("用户名: admin");
            log.info("手机号: 13900139000");
            log.info("密码: 123456");
            log.info("角色: 超级管理员");
            log.info("状态: 激活");
            log.info("邮箱: admin@laundrycare.com");
            log.info("========================");
            
        } catch (Exception e) {
            log.error("创建管理员账号失败: {}", e.getMessage(), e);
        }
    }
}
